/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.controller;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.NotifierDatastore;
import com.apps.datastore.dao.AccountObject;
import com.google.appengine.api.datastore.Key;

public class PreferenceFormController extends HttpServlet {


	private AccountInformationDatastore d = new AccountInformationDatastore();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp){
		try {
			resp.sendRedirect("/preferences.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		// Dont have to check if the user exists. The user is already checked
		// in.
		String phoneNumber = req.getParameter("phone");
		String notifyConfig = req.getParameter("notifyconfig");
		String carrier = req.getParameter("carrier");
		Cookie[] cookies= req.getCookies();
		String user = null;
		for(int i = 0; i < cookies.length; i++) {
			if(cookies[i].getName().equals("user"))
				user = cookies[i].getValue();		
		}
		
		AccountObject lao = d.getAccountObject(user);
		if (lao !=null) {
			
			//Check if any of them are null, 
			//if so, set to whatever they had last time.
			
			if(!notifyConfig.isEmpty()){
				//Error Checking
				long ncfg = Long.parseLong(notifyConfig);
				lao.setNotifyConfig(ncfg);
			}
			if(!phoneNumber.isEmpty())
				lao.setPhoneNumber(phoneNumber);
			if(!carrier.isEmpty())
				lao.setCarrier(carrier);
			d.updateAccountObject(lao);
			resp.sendRedirect("/debug.jsp?msg=preference_update_success");
		}
		else
			resp.sendRedirect("/debug.jsp?msg=preference_update_failed");
			
			
				
		}

	}

